package com.boot2.core.web.xss;

import com.boot2.core.utils.XSSUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 请求包装对象 处理Xss
 * 
 * @author zhangweilin
 * @date 2017年4月5日 下午2:53:37
 * @version V1.0
 * @description
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
	protected static Log loger = LogFactory.getLog(XssHttpServletRequestWrapper.class);
	//上一次包装的请求，
	HttpServletRequest lastOrgRequest = null;

	public XssHttpServletRequestWrapper(HttpServletRequest request) {
		super(request);
		lastOrgRequest = request;
	}

	/**
	 * 覆盖getParameter方法，将参数名和参数值都做xss过滤
	 */
	@Override
	public String getParameter(String name) {
		String value = lastOrgRequest.getParameter(XSSUtil.xssEncode(name));
		if (value != null) {
			value = XSSUtil.xssEncode(value);
		}
		return value;
	}

	/**
	 * 覆盖getParameterValues方法，将参数名和参数值都做xss过滤
	 */
	@Override
	public String[] getParameterValues(String parameter) {
		String[] values = lastOrgRequest.getParameterValues(XSSUtil.xssEncode(parameter));
		if (values == null) {
			return null;
		}
		int count = values.length;
		String[] encodedValues = new String[count];
		for (int i = 0; i < count; i++) {
			encodedValues[i] = XSSUtil.xssEncode(values[i]);
		}
		return encodedValues;
	}

	/**
	 * 获取request的属性时，做xss过滤
	 */
	@Override
	public Object getAttribute(String name) {
		// System.out.println("getAttribute: " + name);
		Object value = lastOrgRequest.getAttribute(XSSUtil.xssEncode(name));
		if (value instanceof String) {
			if (value != null) {
				value = XSSUtil.xssEncode((String) value);
			}
		}
		// System.out.println("value: " + value);
		// if (null != value && value instanceof String)
		// {
		// value = XSSUtil.xssEncode((String) value);
		// }
		return value;
	};

	/**
	 * 覆盖getHeader方法，将参数名和参数值都做xss过滤。<br/>
	 */
	@Override
	public String getHeader(String name) {
		String value = lastOrgRequest.getHeader(XSSUtil.xssEncode(name));
		if (value != null) {
			value = XSSUtil.xssEncode(value);
		}
		return value;
	}



	/**
	 * 获取最原始的request
	 * 
	 * @return
	 */
	public HttpServletRequest getLastOrgRequest() {
		return lastOrgRequest;
	}

	/**
	 * 获取最原始的request的静态方法
	 * 
	 * @return
	 */
	public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
		if (req instanceof XssHttpServletRequestWrapper) {
			return ((XssHttpServletRequestWrapper) req).getLastOrgRequest();
		}
		return req;
	}
}
